<template>
  <header>
    <el-form-item label="班级名称:" label-width="80px" class="label-right-align">
      <el-input v-model="searchQuery" placeholder="请输入班级名称" clearable @keyup.enter="searchClass"></el-input>
    </el-form-item>

    <el-button type="primary" @click="searchClass">
      <el-icon><Search /></el-icon>
      <span>搜索班级信息</span>
    </el-button>

    <el-button type="primary" @click="handleAddClass">
      <el-icon><Plus /></el-icon>
      <span>添加班级信息</span>
    </el-button>

    <el-button type="danger" @click="handleBatchDelete" :disabled="selectedClasses.length === 0">
      <el-icon><Delete /></el-icon>
      <span>批量删除班级信息</span>
    </el-button>
  </header>

  <el-table 
    ref="tableInfo"
    :data="tableData" 
    border 
    stripe 
    v-loading="loading" 
    @selection-change="handleSelectionChange"
    :height="tableHeight"
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column label="封面" width="120">
      <template #default="scope">
        <el-image style="width: 80px; height: 60px" :src="scope.row.cover" fit="cover">
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
      </template>
    </el-table-column>
    <el-table-column prop="name" label="班级名称" sortable="custom" />
    <el-table-column prop="studentCount" label="班级人数" width="100" sortable="custom" />
    <el-table-column prop="headTeacher" label="班主任" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="180" sortable="custom" />
    <el-table-column label="操作" width="300">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleEditClass(scope.row)">编辑班级信息</el-button>
        <el-button link type="danger" size="small" @click="handleDeleteClass(scope.row)">删除班级信息</el-button>
        <el-button link type="info" size="small" @click="handleLinkCourse(scope.row)">关联课程信息</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    layout="total,sizes,->,prev, pager, next,jumper"
    :total="total"
    :default-page-size="pageSize"
    :page-sizes="[10, 20, 30, 50]"
    v-model:current-page="currentPage"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 添加/编辑班级对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加班级信息' : '编辑班级信息'"
    width="500px"
  >
    <el-form :model="classForm" label-width="100px" :rules="rules" ref="classFormRef">
      <el-form-item label="班级名称" prop="name">
        <el-input v-model="classForm.name" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="班级封面" prop="cover">
        <el-upload
          class="avatar-uploader"
          action="/api/upload/image"
          :headers="{ 'Content-Type': 'multipart/form-data' }"
          name="file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="classForm.cover" :src="classForm.cover" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="班主任" prop="headTeacher">
        <el-input v-model="classForm.headTeacher" placeholder="请输入班主任姓名" />
      </el-form-item>
      <el-form-item label="班级人数" prop="studentCount">
        <el-input-number v-model="classForm.studentCount" :min="0" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="classForm.remarks" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitClassForm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 关联课程对话框 -->
  <el-dialog
    v-model="courseDialogVisible"
    title="关联课程信息"
    width="600px"
  >
    <el-table :data="courseList" style="width: 100%" v-loading="courseLoading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="courseName" label="课程名称" />
      <el-table-column prop="courseTeacher" label="授课教师" />
      <el-table-column prop="courseDuration" label="课时" />
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="courseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCourseLink">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, Search, Delete, SwitchButton } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { ClassEntity } from '../model/EduEntity'
import { useRequest } from '../axios'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

// 列表数据
const tableData = ref<ClassEntity[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const selectedClasses = ref<ClassEntity[]>([])

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const classFormRef = ref<FormInstance>()
const classForm = reactive<ClassEntity>(new ClassEntity())
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  headTeacher: [{ required: true, message: '请输入班主任姓名', trigger: 'blur' }]
})

// 课程关联相关
const courseDialogVisible = ref(false)
const courseLoading = ref(false)
const courseList = ref([])
const currentClass = ref<ClassEntity | null>(null)

// 添加新的响应式数据
const tableHeight = ref(600)

// 初始化加载数据
onMounted(() => {
  const documentHeight = document.documentElement.clientHeight
  tableHeight.value = documentHeight - 200 // 减去其他元素的高度
  fetchClassList()
})

// 获取班级列表
const fetchClassList = async () => {
  loading.value = true;
  try {
    const params = {
      name: searchQuery.value,
      page: (currentPage.value - 1) * pageSize.value,
      rp: pageSize.value,
      sortname: '', // 根据排序字段设置
      sortorder: 'asc',
      isActive: 1
    };

    // 获取列表数据
    const response = await axios.post('/api/class/queryClassListByPage', params, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    if (response.data && response.data.success) {
      tableData.value = response.data.data;
    } else {
      ElMessage.error(response.data?.message || '获取数据失败');
    }

    // 获取总数
    const totalResponse = await axios.post('/api/class/queryClassListTotal', params, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    if (totalResponse.data && totalResponse.data.success) {
      total.value = totalResponse.data.data;
    } else {
      ElMessage.error(totalResponse.data?.message || '获取总数失败');
    }
  } catch (error) {
    console.error('获取班级列表失败:', error);
    ElMessage.error('获取班级列表失败');
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchClassList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchClassList()
}

// 搜索班级
const searchClass = () => {
  currentPage.value = 1
  fetchClassList()
}

// 表格选择项变化
const handleSelectionChange = (val: ClassEntity[]) => {
  selectedClasses.value = val
}

// 添加班级
const handleAddClass = () => {
  dialogType.value = 'add'
  Object.assign(classForm, new ClassEntity())
  dialogVisible.value = true
}

// 编辑班级
const handleEditClass = (row: ClassEntity) => {
  dialogType.value = 'edit'
  Object.assign(classForm, row)
  dialogVisible.value = true
}

// 提交表单
const submitClassForm = async () => {
  if (!classFormRef.value) return
  
  await classFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          const response = await axios.post('/api/class/addClass', classForm, {
            headers: { 'Content-Type': 'application/json' }
          });
          if (response.data.success) {
            ElMessage.success('添加班级成功');
          } else {
            ElMessage.error(response.data.message);
          }
        } else {
          const response = await axios.post('/api/class/updateClass', classForm, {
            headers: { 'Content-Type': 'application/json' }
          });
          if (response.data.success) {
            ElMessage.success('编辑班级成功');
          } else {
            ElMessage.error(response.data.message);
          }
        }
        dialogVisible.value = false;
        fetchClassList();
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    }
  })
}

// 删除班级
const handleDeleteClass = (row: ClassEntity) => {
  ElMessageBox.confirm(
    `确定要删除班级 "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.post('/api/class/deleteClass', [row.id], {
        headers: { 'Content-Type': 'application/json' }
      });
      if (response.data.success) {
        ElMessage.success(`删除班级 "${row.name}" 成功`);
        fetchClassList();
      } else {
        ElMessage.error(response.data.message);
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除班级
const handleBatchDelete = () => {
  if (selectedClasses.value.length === 0) {
    ElMessage.warning('请先选择要删除的班级');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedClasses.value.length} 个班级吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = selectedClasses.value.map(item => item.id);
      const response = await axios.post('/api/class/deleteClass', ids, {
        headers: { 'Content-Type': 'application/json' }
      });
      if (response.data.success) {
        ElMessage.success(`批量删除 ${selectedClasses.value.length} 个班级成功`);
        fetchClassList();
      } else {
        ElMessage.error(response.data.message);
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
    // 取消删除
  })
}

// 关联课程
const handleLinkCourse = (row: ClassEntity) => {
  currentClass.value = row
  courseDialogVisible.value = true
  fetchCourseList()
}

// 获取课程列表
const fetchCourseList = async () => {
  courseLoading.value = true
  try {
    // 模拟数据
    setTimeout(() => {
      courseList.value = Array.from({ length: 10 }).map((_, index) => ({
        courseId: `course-${index}`,
        courseName: `课程 ${index + 1}`,
        courseTeacher: `教师 ${index + 1}`,
        courseDuration: Math.floor(Math.random() * 30) + 10
      }))
      courseLoading.value = false
    }, 500)
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
    courseLoading.value = false
  }
}

// 提交课程关联
const submitCourseLink = () => {
  ElMessage.success('关联课程成功')
  courseDialogVisible.value = false
}

// 文件上传相关
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.success) {
    classForm.cover = response.data;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.message || '上传失败');
  }
}

const handleAvatarError = (error: any) => {
  console.error('上传失败:', error);
  ElMessage.error('上传失败');
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('封面图片必须是JPG或PNG格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error('封面图片大小不能超过50MB!');
    return false;
  }
  return true;
}

// 添加注销方法
const logout = () => {
  sessionStorage.setItem("userUuid", "")
  router.push({ path: "/login" })
}
</script>

<style scoped>
.btn > i {
  margin-right: 5px;
}
.btn {
  margin: 5px;
}
header {
  display: flex;
}
.el-button {
  margin: 2px 0 0 5px;
}
.el-form-item {
  margin-bottom: 0;
}

.label-right-align :deep(.el-form-item__label) {
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
}
</style> 